<#include "../common/htmlwrap.ftl">

<@html>

    <@header title="${pageName}">

    <#--jstree style-->
    <link rel="stylesheet" href="${common.staticPath}plugins/jstree/dist/themes/default/style.min.css">

    <style>
        body .fixed-table-container tbody .selected td {
            background-color: #68DC38;
        }
    </style>
    </@header>

<body>

<!-- Content Header (Page header) -->
    <@content_header title='${pageName}'></@content_header>

<section class="content">

    <div class="row">

        <div class="col-md-3 col-sm-4">
            <div class="box box-default">
                <div class="box-header with-border">
                    <i class="fa fa-warning"></i>
                    <h3 class="box-title">总概</h3>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <div id="res_tree" class="tree-demo"></div>
                </div>
                <!-- /.box-body -->
            </div>
        </div>

        <div class="col-md-9 col-sm-8">
            <div class="box">
                <!--<div class="box-header">
                    <h3 class="box-title">Hover Data Table</h3>
                </div>-->
                <!-- /.box-header -->
                <div class="box-body">
                    <form id="search_form" class="form-inline" role="form">
                        <div class="form-group">
                            <span id="search_parent_text"></span>
                            <input type="hidden" class="form-control" name="search_parent" id="search_parent" readonly>
                        </div>
                        <div class="form-group">
                            <select class="form-control" name="search_res_type">
                                <option value="">资源类型</option>
                                <#list resTypes as resource>
                                    <option value="${resource.id}">${resource.name}</option>
                                </#list>
                            </select>
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" name="search_name" id="search_name"
                                   placeholder="资源名字">
                        </div>
                        <button id="btn_search" type="button" class="btn btn-default">搜索</button>
                    </form>
                    <div id="toolbar">
                        <div class="btn-group">
                        <#--<a class="btn btn-default lr-replace"><i class="fa fa-refresh"></i>&nbsp;刷新</a>-->
                            <a class="btn btn-default lr-add page-action" title="新增资源" data-pageId="${add_url}"
                               href="${add_url}"><i
                                    class="fa fa-plus"></i>&nbsp;新增父资源</a>
                        <#--<a class="btn btn-default lr-edit" onclick="toedit()"><i class="fa fa-pencil-square-o"></i>&nbsp;编辑</a>-->
                            <a class="btn btn-default lr-delete" onclick="delete_selection();"><i
                                    class="fa fa-remove"></i>&nbsp;删除</a>
                            <a class="btn btn-default lr-delete" onclick="selectAll()"><i class="fa fa-remove"></i>&nbsp;全选</a>
                            <a class="btn btn-default lr-delete" onclick="reverse_selection()"><i
                                    class="fa fa-remove"></i>&nbsp;反选</a>
                        <#--<a class="btn btn-default lr-viewlog"><i class="fa fa-detail"></i>&nbsp;查看任务日志</a>-->
                        <#--<a class="btn btn-default lr-start"><i class="fa fa-plus"></i>&nbsp;启动</a>-->
                        <#--<a class="btn btn-default lr-stop"><i class="fa fa-trash-o"></i>&nbsp;停止</a>-->
                        </div>
                    </div>
                    <table id="table"
                           data-toggle="table"
                           data-mobile-responsive="true"

                           data-row-style="rowStyle2"
                           data-toolbar="#toolbar"

                           data-query-params="queryParams"
                           data-response-handler="responseHandler"

                           data-url="${common.basePath}/resource/ajaxlist"

                           data-sort-name="url"
                           data-sort-order="desc"

                           data-show-refresh="true"
                           data-show-columns="true"

                           data-click-to-select="true"

                           data-page-list="[10,15]"
                           data-side-pagination="server"
                           data-pagination="true">
                        <thead>
                        <tr>
                            <th data-field="is_checked" data-checkbox="true"></th>
                            <th data-field="id" data-sortable="true">id</th>
                            <th data-field="name">资源名称</th>
                            <th data-field="str_resourceType">类型</th>
                            <th data-field="icon" data-formatter="iconFormatter">图标</th>
                            <th data-field="url" data-sortable="true">url</th>
                            <th data-field="str_status" data-formatter="stateFormatter">状态</th>
                            <th data-field="seq" data-sorter="priceSorter">排序</th>
                            <th data-field="operation" data-click-to-select="false" data-formatter="actionFormatter">
                                操作
                            </th>
                        </tr>
                        </thead>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>

    </div>

</section>


    <@footer_list>

    <!--转换成树的支持-->
    <script src="${common.staticPath}plugins/gtree/tree.js"></script>
    <!--显示js tree-->
    <script src="${common.staticPath}plugins/jstree/dist/jstree.min.js"></script>


    <script type="text/javascript">
        /*function getlayer() {
            return top.layer != null ? top.layer : layer;
        }*/
    </script>

    <!--bootstrap表格相关-->
    <script>

        var edit_url = "${edit_url}";
        var add_url = "${add_url}";

        /**
         * 去编辑按钮
         */
        function toedit() {
            var $table = $('#table');
            var selections = $table.bootstrapTable("getSelections");
            if (selections.length == 1) {
                console.log(selections);
            }
            else if (selections.length == 0) {
                layer.alert("还没有选择行");
            } else if (selections.length > 1) {
                layer.alert("选择的行数量大于1,只能编辑一行");
            }
        }

        /**
         * 全选
         */
        function selectAll() {
            var $table = $('#table');
//            $table.bootstrapTable("checkAll");
            $table.find("input[name=btSelectItem]").each(function () {
                var $input = $(this);
                if (!$input.prop("checked")) {
                    $input.click();
                }
            });
        }

        /**
         * 反选
         */
        function reverse_selection() {
            var $table = $('#table');
            $table.find("input[name=btSelectItem]").each(function () {
                var $input = $(this);
                $input.click();
                if ($input.prop("checked")) {
                } else {

                }
            });
//            console.log($table.bootstrapTable("getSelections"));
        }

        /**
         * 删除所选
         */
        function delete_selection() {
            var $table = $('#table');

            var $list = $table.bootstrapTable("getSelections");

            var ids_arr = [];

            $.each($list, function (n, value) {
                ids_arr.push(value.id);
            });

            if (ids_arr.length > 0) {

                //ajax请求
                $.ajax({
                    url: "${delete_url}",
                    type: "POST",
                    datatype: "json",
                    timeout: 3000,
                    data: {
                        ids: ids_arr
                    },
                    success: function (data, textStatus) {
                        layer.alert(data.msg, function () {
                            if (data.success) {
                                window.location.reload(true);
                            }
                        });
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest + textStatus + errorThrown);
                    }
                });

            } else {
                layer.alert("请选择一条或者多条数据");
            }
        }

        $(function () {
            var $table = $('#table');
            var $search = $('#btn_search');
            $search.click(function () {
                $table.bootstrapTable('selectPage', 1);//选择第一页的时候会刷新表单参数
//                $table.bootstrapTable('refresh');
            });

            $table.on("toggle.bs.table", function (cardView) {
                //cardview和tableview切换

            }).on("post-body.bs.table",function () {
                //table body渲染完成

                //开启bootstrap tooltip
                $("[data-toggle='tooltip']").tooltip();
            });
            /**
             * 选中一行就高亮
             */
            /*$table.on("check.bs.table", function (event, row, $element) {
                var $tr = $element.parents("tr").eq(0);
                $tr.addClass('success');
            });
            $table.on("uncheck.bs.table", function (event, row, $element) {
                var $tr = $element.parents("tr").eq(0);
                $tr.removeClass('success');
//                console.log(event,row,$element);
            });*/

            /*$table.on('click-row.bs.table', function (e, row, $element) {
                console.log("click-row.bs.table", e, row, $element);
                $('.success').removeClass('success');
                $($element).addClass('success');
            });*/
        });

        /**
         * 表单转换成对象
         * @param form
         * @returns {{}}
         */
        function form2Obj(form) {
            var o = {};
//            console.log(form.serializeArray());
            $.each(form.serializeArray(), function (index) {
//                console.log(this);
                if (o[this['name']]) {
                    o[this['name']] = o[this['name']] + "," + this['value'];
                } else {
                    o[this['name']] = this['value'];
                }
            });
            return o;
        }

        function queryParams(params) {
//            console.log(params);
            $.extend(true, params, form2Obj($("#search_form")));

//            var params = {};
//            params = ;
            /*$('#toolbar').find('input[name]').each(function () {
                params[$(this).attr('name')] = $(this).val();
            });*/
            return params;
        }


        /*数据格式化*/

        function iconFormatter(value, row) {
            return '<span class="' + row.icon + '" title="' + row.icon + '" data-toggle="tooltip" data-placement="bottom"></span>';
        }

        /**
         * 状态格式化
         * @param value
         * @param row
         * @returns {*}
         */
        function stateFormatter(value, row) {

            if (row.status == 'OPEN') {
                return '<span class="label label-sm label-success"> 开 </span>';
            }
            else if (row.status == 'CLOSE') {
                return '<span class="label label-sm label-warning"> 关 </span>';
            } else {
                return value;
            }

        }

        /**
         * 创建bootstrap的按钮
         * @param clazz
         * @param icon
         * @param href
         * @param title
         * @param text
         * @returns {string}
         */
        function createButtonText(clazz, icon, href, title, text) {
            var text = '<a class="btn btn-default page-action' + clazz + '" href="' + href + '" data-toggle="tooltip" data-placement="bottom" ' +
                    'data-pageId="' + href + '" title="' + title + '">' +
                    '<i class="' + icon + '"></i>' + text + '</a>';
            return text;
        }

        function actionFormatter(value, row) {

            var _edit_url = edit_url + "?id=" + row.id;
            var text = createButtonText("", "fa fa-edit", _edit_url, "编辑[" + row.name + "]", "");
            var _add_url = add_url + "?pid=" + row.pid;
            text += createButtonText("", "fa fa-plus", _add_url, "为[" + row.name + "]新增子资源", "");
            return text;

        }

        function rowStyle(row, index) {
            if (index % 2 === 0) {
                return {
                    classes: 'active'
                };
            }
            return {};
        }

        function rowStyle2(row, index) {
            var classes = ['success', 'info', 'warning', 'danger'];//'active',
            if (index % 2 === 0) {//&& index / 2 < classes.length)
                return {
                    classes: classes[(index / 2) % classes.length]
                };
            }
            return {};
        }

        function responseHandler(res) {
            if (res.success) {
                /* 已经用formatter替换
                $.each(res.obj.rows, function (n, value) {
                    //图标
                    value.icon = '<span class="' + value.icon + '" title="' + value.icon + '" data-toggle="tooltip" data-placement="bottom"></span>';
                    //编辑按钮
                    value.operation = createButtonText("", "fa fa-edit", "编辑[" + value.name + "]", "");
//                    '<button class="btn btn-default" data-toggle="tooltip" data-placement="bottom"><i class="fa fa-edit"></i>编辑</button>';
                    value.operation += createButtonText("", "fa fa-plus", "为[" + value.name + "]新增子资源", "");
//                    '<button class="btn btn-default" data-toggle="tooltip" data-placement="bottom"><i class="fa fa-plus">新增子资源</i>';
                });
                */
                return res.obj;
            } else {
                layer.alert(res.msg);
            }
            return null;
        }
    </script>

    <!--菜单相关-->
    <script>
        //显示菜单树
        $(document).ready(function () {

            var treeUrl = "${common.basePath}/resource/ajaxtree";

            //jstree数中一项有text,icon和chilren就足够了
            $('#res_tree').jstree({
                'plugins': ["wholerow", "types"],
                'core': {
                    "themes": {
                        "responsive": false
                    },
                    'data': function (node, callback) {
                        console.log("jstree.core.data.function:");
                        console.log(node);
                        $.ajax({
                            url: treeUrl,
                            type: "POST",
                            datatype: "json",
                            //timeout: 3000,
                            data: {
                                "pid": node.id
                            }
                        }).done($.proxy(function (data, status, xhr) {
                            if (data.success) {
                                if (data.obj instanceof Array) {
                                    $.each(data.obj, function (n, value) {
                                        //value.text = value.name;
                                        if (value.childCount > 0) {
                                            value.children = true;
                                        }
                                    });
                                } else if (typeof (data.obj) == "object") {
                                    $.each(data.obj.children, function (n, value) {
                                        //value.text = value.name;
                                        if (value.childCount > 0) {
                                            value.children = true;
                                        }
                                    });
                                }
                                callback(data.obj);
                            } else {
                                layer.alert(data.msg);
                            }
                        }, this)).fail($.proxy(function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert(errorThrown);
                        }, this));
                    }
                },
                "types": {
                    "default": {
                        "icon": "fa fa-folder icon-state-warning icon-lg"
                    },
                    "file": {
                        "icon": "fa fa-file icon-state-warning icon-lg"
                    }
                }
            }).bind('select_node.jstree', function (event, selected) {  //绑定的点击事件
                console.log("select_node.jstree");
//                console.log(selected);
                if (selected.node.original.id == "0") {
                    //设置input hidden的值域
                    $("#search_parent").val(null);//显示全部,而不需要pid
                    //
                    $("#search_parent_text").text("显示全部");
                    $("#table").bootstrapTable("refresh");
                } else {
                    if (selected.node.original.childCount > 0) {//规定有子目录的才搜索,selected.node.children.length > 0
                        //设置input hidden的值域
                        $("#search_parent").val(selected.node.id);
                        //
                        $("#search_parent_text").text("当前选择父目录:" + selected.node.text);
                        $("#table").bootstrapTable("refresh");
                    }
                }

            });

            /*$.getJSON(treeUrl, {}, function (list) {
                for (var i = 0; i < list.length; i++) {
                    list[i]['text'] = list[i]['name'];
                }
                //转化为jstree识别的json格式
                var menuTree = $.GTree({
                    data: list,
                    options: {
                        child_field: "children"
                    }
                });
//                console.log(menuTree);

            });*/
        });
    </script>

    </@footer_list>

</body>
</@html>